<template>
  <div class="app-container leaguer">
    <!-- 工具栏 start-->
    <EzForm
      ref="menuForm"
      :formMap="formMap"
      v-model="formData"
      @search="searchRequest"
    ></EzForm>
    <BtnGroup ref="btnGroup" :btns="btns" @handle="handleBtnGroup" />

    <!-- 工具栏 end-->

    <div class="">
      <el-table
        ref="table"
        :data="lists"
        :height="st"
        v-loading="loading"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        row-key="id"
        lazy
        :tree-props="{ hasChildren: 'subOrder' }"
      >
        <el-table-column type="selection" width="55"></el-table-column>

        <el-table-column label="姓名" align="center" width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="登录账号" align="center" width="150">
          <template slot-scope="scope">
            <span>{{ scope.row.username }}</span>
          </template>
        </el-table-column>

        <el-table-column label="账号角色" width="150" align="center">
          <template slot-scope="scope">
            <p v-for="item in dict_list.role_dict" :key="item.value">
              <span v-if="item.value === scope.row.role_id">{{ item.label }}</span>
            </p>
          </template>
        </el-table-column>
        <el-table-column label="账号状态" width="150" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.state == 1 ? "开启" : "暂停" }}</span>
          </template>
        </el-table-column>

        <el-table-column label="上次访问时间" width="200">
          <template slot-scope="scope">
            <span>{{ scope.row.last_login_time }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" width="200">
          <template slot-scope="scope">
            <span>{{ scope.row.created_at }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建人" width="200">
          <template slot-scope="scope">
            <span>{{ scope.row.created_by }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template slot-scope="scope">
            <el-button
              v-auth="'/admin/auth/user/action'"
              type="text"
              size="mini"
              @click="handleAction(scope.row)"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        :page="currentPage"
        :total="total"
        :size="pageSize"
        @sizeChange="sizeChange"
        @currentChange="currentChange"
        ref="paginationTotal"
      ></pagination>
    </div>

    <!--新建弹框-->
    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogTitle"
      :before-close="modalClose"
      :close-on-press-escape="false"
      append-to-body
    >
      <div v-loading="loading">
        <el-form
          :model="actionForm"
          ref="actionForm"
          label-width="120px"
          size="small"
          :rules="rules"
        >
          <el-form-item label="账户角色" prop="role_id" align="left">
            <el-select
              size="small"
              clearable
              placeholder="请选择账户角色"
              v-model="actionForm.role_id"
            >
              <el-option
                v-for="(item, index) in roleDict"
                :key="index"
                :label="item.label"
                :value="item.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="用户姓名：" prop="name">
            <el-input
              v-model.trim="actionForm.name"
              placeholder="请输入用户姓名"
              maxlength="50"
              @change="rowChange"
            />
          </el-form-item>

          <el-form-item label="登录账号：" prop="username">
            <el-input v-model.trim="actionForm.username" />
          </el-form-item>
          <el-form-item label="登录密码：" prop="psw">
            <el-input v-model.trim="actionForm.psw" show-password />
          </el-form-item>
        </el-form>

        <div class="tool2">
          <el-button @click="handleSubmit" type="primary" size="medium"
            >确定</el-button
          >
          <el-button @click="modalClose" size="medium">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      formMap: [
        {
          label: "姓名",
          key: "name",
          type: "input",
        },
        {
          label: "登录账号",
          key: "username",
          type: "input",
        },
        {
          label: "账户角色",
          key: "role_id",
          type: "select",
          options: [],
        },
        {
          label: "创建日期",
          key: "created_at",
          type: "cratedate",
        },
      ],
      formData: {
        phone: "",
        name: "",
        username: "",
        created_at: "",
      },
      btns: [
        { title: "暂停账号", pos: "right", handle: "close" },
        { title: "开启账号", pos: "right", handle: "open" },
        { title: "新增", pos: "right", handle: "new" },
      ],
      lists: [],
      loading: true,
      dialogExamine: false,
      examineList: "",
      examineListLength: 0,
      // 默认显示第几页
      currentPage: 1,
      // 总条数，根据接口获取数据长度(注意：这里不能为空)
      total: 0,
      // 个数选择器（可修改）
      pageSizes: [50, 100, 200],
      // 默认每页显示的条数（可修改）
      pageSize: 30,

      st: 0,
      dialogVisible: false,
      dialogTitle: "创建账号",

      dict_list: {
        type_list: [],
        role_list: [],
        state_list: [],
        warehouse_list: [],
        is_parent_list: [],
        merchants_role_list: [],
      },

      actionForm: {
        type: "",
        id: "",
        role_id: "",
        username: "",
        psw: "",
        name: "",
        phone: "",
        name: "",
        warehouse_id: "",
        merchants_id: "",
      },

      created_at: [],

      searchParams: {
        phone: "",
        name: "",
        username: "",
        merchants_id: "", //商户
        warehouse_name: "", //仓库
        created_at_begin: "",
        created_at_end: "",
        role_id: "", //角色
        state: "",
        type: "",
        is_parent: "",
      },

      dialogloading: true,
      classify_name: "",

      department_id: [],
      departmentDrops: {
        value: "id",
        label: "name",
        checkStrictly: true,
      },

      synchroUserLodaing: false,
      addFrom: {
        phone: "",
        name: "",
      },
      // 验证表单
      rules: {
          // 角色
        role_id: [{ required: true, message: "请选择角色", trigger: "change" }],
        name: [{ required: true, message: "请输入用户姓名", trigger: "blur" }],

        // 请输入登录账号
        username: [
          { required: true, message: "请输入登录账号", trigger: "blur" },
        ],
        // 登录密码
        psw: [{ required: true, message: "请输入登录密码", trigger: "blur" }],
      },
      chooseList: [], //选中处理的列表
      roleDict: [], //角色
    };
  },
  created() {
    this.handleInit();
  },

  mounted() {
    let that = this;
    that.$util.autoHeight(that, that.$refs.table.$el);
  },
  methods: {
    /**
     * 头部按钮列表
     */
    handleBtnGroup(evt) {
      let { handle } = evt;
      switch (handle) {
        case "new":
          this.dialogVisible = true;
          break;
        case "open":
          this.settingState(1);
          break;
        case "close":
          this.settingState(0);
          break;
        // case "pass":
        //   this.exmaineApproved();
        //   break;
        // case "Refuse":
        //   this.dialogExamineBtn();
        //   break;

        // case "log":
        //   this.toLog();
        //   break;
        default:
          break;
      }
    },
    // 开启或关闭账号状态
    settingState(state) {
      // state 暂停-0  开启-1
      let message = state == 1 ? "开启" : "暂停";
      let that = this;
      let _selectData = that.$refs.table.selection;
      let ids = [];
      console.log("_selectData", _selectData, state);
      if (state == 0) {
        _selectData.forEach((item, i) => {
          if (item.user_state == 1) {
            ids.push(item.id);
          }
        });
      } else {
        _selectData.forEach((item, i) => {
          if (item.user_state == 0) {
            ids.push(item.id);
          }
        });
      }
      console.log("_selectData", _selectData, state, ids);
      if (ids.length <= 0) {
        that.$message({ type: "error", message: "请选择需要操作的用户！" });
        return false;
      }

      //请求接口
      async function doAction(ids) {
        try {
          that.dialogloading = true;
          const { result } = await that.$.authority.authuserSettingState({
            ids: ids,
            user_state: state,
          });
          that.dialogloading = false;
          that.dialogVisible = false;

          if (result.row == 0) {
            that.$message({ type: "success", message: "未有处理数据" });
          } else {
            that.$message({ type: "success", message: "提交成功" });
            that.handleSearch();
          }
        } catch (e) {
          that.dialogloading = false;
        }
      }

      this.$confirm(
        "确定" + message + "此用户状态, 是否继续?",
        "修改用户状态",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          doAction(ids);
        })
        .catch(() => {
          //取消的提示
        });
    },

    dialogExamineBtn() {
      let that = this;

      let _selectData = that.$refs.table.selection;
      let ids = [];
      let username = [];
      _selectData.forEach((item, i) => {
        if (item.state == 1) {
          ids.push(item.id);
          username.push(item.username);
        }
      });
      console.log("_selectData", _selectData, ids);

      if (ids.length <= 0) {
        that.$message({ type: "error", message: "请选择需要操作的用户！" });
        return false;
      }
      that.dialogExamine = true;
      that.examineIds = ids;
      that.examineListLength = username.length;
      that.examineList = username.toString();
    },

    // 关闭对话框
    modalClose() {
      this.dialogVisible = false;
      this.dialogExamine = false;
    },

    // 新增，编辑
    async handleAction(row = null) {
      let that = this;

      if (row != null) {
        //编辑回显
        that.dialogTitle = "编辑用户";

        that.actionForm.id = row.id;
        that.actionForm.role_id = row.role_id;
        that.actionForm.username = row.username;
        that.actionForm.psw = "";
        that.actionForm.name = row.name;
        that.actionForm.phone = row.phone;

        that.actionForm.value = row.value;
        that.actionForm.classify_id = row.classify_id;
        that.actionForm.weight_unit_id = row.weight_unit_id;
        that.actionForm.package_unit_id = row.package_unit_id;
        that.actionForm.id = row.id;
      } else {
        that.dialogTitle = "创建用户";

        that.actionForm.id = "";
        that.actionForm.role_id = "";
        that.actionForm.username = "";
        that.actionForm.psw = "";
        that.actionForm.name = "";
        that.actionForm.phone = "";
      }

      that.dialogloading = false;
      that.dialogVisible = true;
    },

    // 提交
    async handleSubmit(e) {
      let that = this;
      that.$refs.actionForm.validate(async (v) => {
        if (!v) {
          return false;
        }
        try {
          that.dialogloading = true;
          that.actionForm.role_id != "" ? that.actionForm.role_id : 0;
          that.actionForm.warehouse_id != "" ? that.actionForm.warehouse_id : 0;
          that.actionForm.merchants_id != ""
            ? that.actionForm.merchants_id
            : that.merchantsId;
          let { result } = await that.$.authority.authUserAction(
            that.actionForm
          );
          that.dialogloading = false;
          that.dialogVisible = false;
          that.handleSearch();
        } catch (e) {
          that.dialogloading = false;
        }
      });
    },

    // 搜索
    handleSearch(statu) {
      this.currentPage = 1;
      this.handleRequest();
    },

    // 弹框的行更改
    rowChange(e) {
      console.log(e);
    },

    handleSizeChange(e) {
      console.log(e);
    },
    handleCurrentChange(e) {
      console.log(e);
    },
    searchRequest() {
      this.currentPage = 1;
      this.handleRequest();
    },
    sizeChange(e) {
      let that = this;
      that.currentPage = 1;
      that.pageSize = e;
      that.handleRequest();
    },
    currentChange(e) {
      this.currentPage = e;
      this.handleRequest();
    },

    //请求列表
    async handleRequest(statu) {
      const that = this;
      let { currentPage, pageSize, created_at, department_id, formData } = that;
      let o = { page_size: pageSize, page: currentPage };
      o.created_at_begin = !!formData.created_at
        ? formData.created_atcreated_at[0]
        : "";
      o.created_at_end = !!formData.created_atcreated_at
        ? formData.created_atcreated_at[1]
        : "";
      that.$util.ext(that.formData, o);

      if (department_id) {
        that.formData.department_id = department_id[department_id.length - 1];
      }

      try {
        that.loading = true;
        let { result } = await that.$.authority.authUserIndex(that.formData);
        that.total = result.pagination.total_count;
        if (!statu) {
          that.$refs.table.bodyWrapper.scrollTop = 0;
        }
        that.lists = result.list;
        that.loading = false;
      } catch (e) {
        that.loading = false;
      }
    },

    //初始化
    async handleInit() {
      const that = this;
      const { result } = await that.$.authority.authUserDict();
      that.dict_list = result;

      that.formMap[2].options = result.role_dict;

      that.roleDict = result.role_dict;

      await this.handleRequest();
    },

    handleSelectionChange(e) {
      console.log(e);
    },
  },
};
</script>

<style lang="scss" scoped>
.ctime {
  overflow: hidden;
  width: 450px;
}
.el-date-editor--datetimerange.el-input__inner {
  width: 350px;
}

.el-range-editor--small .el-range-input {
  width: 150px;
}
</style>
<style scoped>
.cell {
  text-align: center;
}
</style>
